<template>
	<view class="yomi-container">
		<!-- 头部欢迎区域 -->
		<view class="header-section">
			<view class="yomi-avatar">
				<text class="avatar-text">YOMI</text>
			</view>
			<text class="welcome-text">您好！我是您的AI运动教练YOMI</text>
			<text class="subtitle">让我帮助您提升运动表现</text>
		</view>

		<!-- 主要功能区域 -->
		<view class="main-functions">
			<!-- 视频上传 -->
			<view class="function-card upload-card" @click="uploadVideo">
				<view class="card-header">
					<uni-icons type="videocam" size="28" color="#667eea"></uni-icons>
					<text class="card-title">上传运动视频</text>
				</view>
				<text class="card-desc">上传您的运动视频，获得专业AI分析</text>
			</view>

			<!-- 分析历史 -->
			<view class="function-card" @click="viewAnalysisHistory">
				<view class="card-header">
					<uni-icons type="bars" size="28" color="#667eea"></uni-icons>
					<text class="card-title">分析历史</text>
				</view>
				<text class="card-desc">查看您的运动分析记录和进步轨迹</text>
			</view>
		</view>

		<!-- AI对话区域 -->
		<view class="chat-section">
			<text class="section-title">AI智能指导</text>
			
			<!-- 快速操作 -->
			<view class="quick-actions">
				<view class="action-btn" @click="quickAsk">
					<uni-icons type="chat" size="20" color="#667eea"></uni-icons>
					<text class="action-text">快速提问</text>
				</view>
				<view class="action-btn" @click="viewConversations">
					<uni-icons type="list" size="20" color="#667eea"></uni-icons>
					<text class="action-text">对话历史</text>
				</view>
			</view>

			<!-- 推荐问题 -->
			<view class="suggestions" v-if="suggestedQuestions.length > 0">
				<text class="suggestions-title">推荐问题</text>
				<view class="question-list">
					<view class="question-item" 
						  v-for="(question, index) in suggestedQuestions" 
						  :key="index"
						  @click="askQuestion(question)">
						<uni-icons type="help" size="16" color="#667eea"></uni-icons>
						<text class="question-text">{{ question }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 最近分析结果 -->
		<view class="recent-section" v-if="recentResults.length > 0">
			<text class="section-title">最近分析</text>
			<view class="results-list">
				<view class="result-item" 
					  v-for="result in recentResults" 
					  :key="result.id"
					  @click="viewResultDetail(result)">
					<view class="result-info">
						<text class="result-title">{{ result.sportType || '运动分析' }}</text>
						<text class="result-time">{{ formatTime(result.createdAt) }}</text>
						<view class="result-status" :class="getStatusClass(result.status)">
							<text class="status-text">{{ getStatusText(result.status) }}</text>
						</view>
					</view>
					<uni-icons type="right" size="16" color="#ccc"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 运动类型选择模态框 -->
		<view class="modal-overlay" v-if="showSportTypeModal" @click="closeSportTypeModal">
			<view class="sport-type-modal" @click.stop>
				<text class="modal-title">选择运动类型</text>
				<view class="sport-types">
					<view class="sport-type-item" 
						  v-for="type in sportTypes" 
						  :key="type.value"
						  @click="selectSportType(type)">
						<text class="sport-type-text">{{ type.label }}</text>
					</view>
				</view>
				<view class="modal-actions">
					<button class="cancel-btn" @click="closeSportTypeModal">取消</button>
				</view>
			</view>
		</view>

		<!-- 分析结果详情模态框 -->
		<view class="modal-overlay" v-if="showResultModal" @click="closeResultModal">
			<view class="result-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">分析结果</text>
					<uni-icons type="closeempty" size="24" color="#999" @click="closeResultModal"></uni-icons>
				</view>
				<view class="result-content" v-if="selectedResult">
					<text class="result-type">{{ selectedResult.sportType || '运动分析' }}</text>
					<text class="result-summary">{{ selectedResult.summary || '分析完成，点击查看详细结果' }}</text>
					<view class="result-actions">
						<button class="action-btn primary" @click="viewDetailedResult">查看详细分析</button>
						<button class="action-btn" @click="createAIConversation">开始AI指导</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getSuggestedQuestions, quickAsk as apiQuickAsk, createConversation, getUserConversations } from '@/api/modules/AiGuidance.js'
import { uploadAndAnalyze, getUserAnalysisResults, checkAnalysisStatus, getDetailedAnalysisResult } from '@/api/modules/video.js'
import { getAnalysisResultsByUserId } from '@/api/modules/userAnalysisResult.js'
import { getBaseURL } from '@/api/config.js'

const suggestedQuestions = ref([])
const recentResults = ref([])
const showSportTypeModal = ref(false)
const showResultModal = ref(false)
const selectedResult = ref(null)
const currentVideoFile = ref(null)
const pollingTimers = ref(new Map())

// 运动类型选项
const sportTypes = ref([
	{ label: '通用运动', value: 'general' },
	{ label: '跑步', value: 'running' },
	{ label: '篮球', value: 'basketball' },
	{ label: '网球', value: 'tennis' },
	{ label: '游泳', value: 'swimming' },
	{ label: '健身', value: 'fitness' }
])

// 模拟推荐问题
const mockQuestions = [
	'如何改善我的跑步姿势？',
	'训练后如何正确拉伸？',
	'如何避免运动损伤？',
	'制定合适的训练计划',
	'我的动作标准吗？'
]

onMounted(() => {
	loadData()
})

onUnmounted(() => {
	// 清理所有轮询定时器
	pollingTimers.value.forEach(timer => clearInterval(timer))
	pollingTimers.value.clear()
})

// 加载页面数据
const loadData = async () => {
	await Promise.all([
		loadSuggestedQuestions(),
		loadRecentResults()
	])
}

// 加载推荐问题
const loadSuggestedQuestions = async () => {
	try {
		// 获取最新完成的分析结果用于推荐问题
		const latestResult = recentResults.value.find(r => r.status === 'COMPLETED')
		
		if (latestResult) {
			const response = await getSuggestedQuestions({
				resultId: latestResult.resultId,
				sportType: latestResult.sportType || 'general'
			})
			suggestedQuestions.value = response || mockQuestions
		} else {
			// 没有分析结果时使用通用推荐问题
			suggestedQuestions.value = mockQuestions
		}
	} catch (error) {
		console.error('加载推荐问题失败:', error)
		suggestedQuestions.value = mockQuestions
	}
}

// 加载最近的分析结果
const loadRecentResults = async () => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			// 用户未登录时显示空列表
			recentResults.value = []
			return
		}
		
		const response = await getAnalysisResultsByUserId(userId)
		if (response && response.data) {
			recentResults.value = response.data.slice(0, 3)
		}
	} catch (error) {
		console.error('加载分析历史失败:', error)
		// 网络错误时使用模拟数据（仅在开发环境）
		if (process.env.NODE_ENV === 'development') {
			recentResults.value = [
				{
					id: 1,
					resultId: 'result_001',
					sportType: '跑步分析',
					status: 'COMPLETED',
					createdAt: new Date().toISOString(),
					summary: '您的跑步姿势整体良好，建议改善步频节奏'
				},
				{
					id: 2,
					resultId: 'result_002',
					sportType: '篮球投篮',
					status: 'ANALYZING',
					createdAt: new Date(Date.now() - 86400000).toISOString()
				}
			]
		} else {
			recentResults.value = []
		}
	}
}

// 上传视频
const uploadVideo = () => {
	// 检查用户是否已登录
	if (!checkUserLogin()) {
		return
	}
	
	uni.chooseVideo({
		sourceType: ['camera', 'album'],
		maxDuration: 60,
		camera: 'back',
		success: (res) => {
			console.log('选择的视频:', res)
			currentVideoFile.value = res
			showSportTypeModal.value = true
		},
		fail: (error) => {
			console.error('选择视频失败:', error)
			uni.showToast({
				title: '选择视频失败',
				icon: 'none'
			})
		}
	})
}

// 选择运动类型
const selectSportType = async (type) => {
	const userId = getCurrentUserId()
	if (!userId) {
		closeSportTypeModal()
		uni.showToast({
			title: '用户信息获取失败',
			icon: 'none'
		})
		return
	}
	
	closeSportTypeModal()
	
	uni.showLoading({
		title: '上传分析中...'
	})
	
	try {
		// 实际的视频上传
		const formData = new FormData()
		
		// 在uni-app中需要使用uni.uploadFile
		const uploadResult = await new Promise((resolve, reject) => {
			uni.uploadFile({
				url: getBaseURL() + '/video/upload',
				filePath: currentVideoFile.value.tempFilePath,
				name: 'video',
				formData: {
					userId: userId.toString(), // 确保传递字符串格式
					sportType: type.value
				},
				header: {
					'Authorization': `Bearer ${getToken()}`
				},
				success: (res) => {
					try {
						const data = JSON.parse(res.data)
						if (data.code === 200) {
							resolve(data.data)
						} else {
							reject(new Error(data.message || '上传失败'))
						}
					} catch (e) {
						reject(new Error('响应解析失败'))
					}
				},
				fail: reject
			})
		})
		
		uni.hideLoading()
		uni.showToast({
			title: '上传成功，正在分析...',
			icon: 'success'
		})
		
		// 开始轮询检查分析状态
		startStatusPolling(uploadResult.resultId)
		
		// 刷新分析历史
		loadRecentResults()
		
	} catch (error) {
		uni.hideLoading()
		console.error('上传失败:', error)
		uni.showToast({
			title: error.message || '上传失败，请重试',
			icon: 'none'
		})
	}
}

// 快速提问
const quickAsk = async () => {
	uni.showModal({
		title: '向YOMI提问',
		content: '请输入您的问题',
		editable: true,
		placeholderText: '例如：如何改善跑步姿势？',
		success: async (res) => {
			if (res.confirm && res.content.trim()) {
				await handleQuestion(res.content.trim())
			}
		}
	})
}

// 点击推荐问题
const askQuestion = async (question) => {
	await handleQuestion(question)
}

// 处理问题
const handleQuestion = async (question) => {
	try {
		uni.showLoading({
			title: 'YOMI思考中...'
		})
		
		// 获取最新的分析结果ID用于AI指导
		const latestResult = recentResults.value.find(r => r.status === 'COMPLETED')
		const resultId = latestResult?.resultId || 'general'
		const sportType = latestResult?.sportType || 'general'
		
		const result = await apiQuickAsk({
			resultId: resultId,
			sportType: sportType,
			question: question
		})
		
		uni.hideLoading()
		
		// 显示AI回答
		uni.showModal({
			title: 'YOMI的回答',
			content: result.answer || '根据您的运动分析结果，我建议您注意以下几点...',
			showCancel: false,
			confirmText: '知道了'
		})
		
	} catch (error) {
		uni.hideLoading()
		console.error('提问失败:', error)
		uni.showToast({
			title: '提问失败，请重试',
			icon: 'none'
		})
	}
}

// 查看分析历史
const viewAnalysisHistory = () => {
	uni.navigateTo({
		url: '/pages/analysis/list'
	})
}

// 查看对话历史
const viewConversations = async () => {
	try {
		// 获取最新的分析结果ID
		const latestResult = recentResults.value.find(r => r.status === 'COMPLETED')
		
		if (!latestResult) {
			uni.showToast({
				title: '请先完成运动分析',
				icon: 'none'
			})
			return
		}
		
		uni.showLoading({
			title: '加载对话历史...'
		})
		
		const conversations = await getUserConversations(latestResult.resultId)
		
		uni.hideLoading()
		
		if (!conversations || conversations.length === 0) {
			uni.showToast({
				title: '暂无对话历史',
				icon: 'none'
			})
			return
		}
		
		// 显示对话列表
		const conversationTitles = conversations.map((conv, index) => 
			`对话${index + 1} - ${formatTime(conv.createTime)}`
		)
		
		uni.showActionSheet({
			itemList: conversationTitles,
			success: (res) => {
				const selectedConv = conversations[res.tapIndex]
				viewConversationDetail(selectedConv.conversationId)
			}
		})
		
	} catch (error) {
		uni.hideLoading()
		console.error('加载对话历史失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	}
}

// 查看对话详情
const viewConversationDetail = async (conversationId) => {
	try {
		uni.showLoading({
			title: '加载对话详情...'
		})
		
		const conversationDetail = await getConversation(conversationId)
		
		uni.hideLoading()
		
		// TODO: 跳转到对话详情页面
		// uni.navigateTo({
		//   url: `/pages/conversation/detail?conversationId=${conversationId}`
		// })
		
		// 临时显示对话摘要
		uni.showModal({
			title: '对话历史',
			content: '对话详情功能开发中，将显示完整的问答记录...',
			showCancel: false
		})
		
	} catch (error) {
		uni.hideLoading()
		console.error('加载对话详情失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	}
}

// 查看结果详情
const viewResultDetail = (result) => {
	if (result.status === 'COMPLETED') {
		uni.navigateTo({
			url: `/pages/analysis/detail?resultId=${result.resultId}&id=${result.id}`
		})
	} else {
		selectedResult.value = result
		showResultModal.value = true
	}
}

// 查看详细分析
const viewDetailedResult = async () => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		uni.showLoading({
			title: '加载详细分析...'
		})
		
		const result = selectedResult.value
		const detailedResult = await getDetailedAnalysisResult(result.resultId, {
			userId: userId,
			sportType: result.sportType
		})
		
		uni.hideLoading()
		closeResultModal()
		
		// TODO: 跳转到详细分析页面，传递分析数据
		// uni.navigateTo({
		//   url: `/pages/analysis/detail?resultId=${result.resultId}`,
		//   success: () => {
		//     // 可以通过eventChannel传递复杂数据
		//   }
		// })
		
		// 临时显示分析摘要
		uni.showModal({
			title: '分析结果',
			content: detailedResult.summary || '详细分析数据已加载，请在详细分析页面查看完整报告。',
			showCancel: false
		})
		
	} catch (error) {
		uni.hideLoading()
		console.error('加载详细分析失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	}
}

// 创建AI指导会话
const createAIConversation = async () => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		const result = selectedResult.value
		const response = await createConversation({
			resultId: result.resultId,
			sportType: result.sportType,
			userId: userId
		})
		
		uni.showToast({
			title: '已创建AI指导会话',
			icon: 'success'
		})
		
		closeResultModal()
		
		// TODO: 跳转到对话页面
	} catch (error) {
		console.error('创建会话失败:', error)
		uni.showToast({
			title: '创建会话失败',
			icon: 'none'
		})
	}
}

// 关闭模态框
const closeSportTypeModal = () => {
	showSportTypeModal.value = false
	currentVideoFile.value = null
}

const closeResultModal = () => {
	showResultModal.value = false
	selectedResult.value = null
}

// 开始状态轮询
const startStatusPolling = (resultId) => {
	const userId = getCurrentUserId()
	
	const timer = setInterval(async () => {
		try {
			const statusResult = await checkAnalysisStatus(resultId, { userId })
			
			// 更新本地结果状态
			const index = recentResults.value.findIndex(r => r.resultId === resultId)
			if (index !== -1) {
				recentResults.value[index].status = statusResult.status
				
				// 如果分析完成，停止轮询
				if (statusResult.status === 'COMPLETED' || statusResult.status === 'FAILED') {
					clearInterval(timer)
					pollingTimers.value.delete(resultId)
					
					if (statusResult.status === 'COMPLETED') {
						uni.showToast({
							title: '分析完成！',
							icon: 'success'
						})
						// 重新加载结果以获取最新数据
						loadRecentResults()
					} else {
						uni.showToast({
							title: '分析失败',
							icon: 'none'
						})
					}
				}
			}
		} catch (error) {
			console.error('检查状态失败:', error)
		}
	}, 5000) // 每5秒检查一次
	
	pollingTimers.value.set(resultId, timer)
}

// 获取当前用户ID
const getCurrentUserId = () => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if (userInfo && userInfo.id) {
			// 确保返回数字类型
			return typeof userInfo.id === 'string' ? parseInt(userInfo.id) : userInfo.id
		}
		
		// 如果没有用户信息，提示用户登录
		console.warn('用户未登录或用户信息缺失')
		return null
	} catch (error) {
		console.error('获取用户ID失败:', error)
		return null
	}
}

// 获取Token
const getToken = () => {
	return uni.getStorageSync('accessToken') || ''
}

// 检查用户登录状态
const checkUserLogin = () => {
	const userId = getCurrentUserId()
	const token = getToken()
	
	if (!userId || !token) {
		uni.showModal({
			title: '提示',
			content: '请先登录后再使用此功能',
			showCancel: false,
			confirmText: '去登录',
			success: () => {
				uni.switchTab({
					url: '/pages/user/user'
				})
			}
		})
		return false
	}
	
	return true
}

// 工具函数
const formatTime = (timeStr) => {
	const date = new Date(timeStr)
	const now = new Date()
	const diff = now - date
	
	if (diff < 60000) return '刚刚'
	if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
	if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
	return `${Math.floor(diff / 86400000)}天前`
}

const getStatusClass = (status) => {
	switch (status) {
		case 'COMPLETED': return 'status-completed'
		case 'ANALYZING': return 'status-analyzing'
		case 'FAILED': return 'status-failed'
		default: return 'status-pending'
	}
}

const getStatusText = (status) => {
	switch (status) {
		case 'COMPLETED': return '已完成'
		case 'ANALYZING': return '分析中'
		case 'FAILED': return '失败'
		default: return '等待中'
	}
}
</script>

<style lang="scss" scoped>
.yomi-container {
	background-color: #f8f9fa;
	min-height: 100vh;
}

.header-section {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 30px 20px;
	text-align: center;
	
	.yomi-avatar {
		width: 60px;
		height: 60px;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 15px auto;
		
		.avatar-text {
			font-size: 20px;
			font-weight: bold;
			color: white;
		}
	}
	
	.welcome-text {
		font-size: 20px;
		font-weight: bold;
		color: white;
		display: block;
		margin-bottom: 8px;
	}
	
	.subtitle {
		font-size: 14px;
		color: rgba(255, 255, 255, 0.8);
	}
}

.main-functions {
	padding: 20px;
	display: grid;
	grid-template-columns: 1fr;
	gap: 15px;
	
	.function-card {
		background: white;
		padding: 20px;
		border-radius: 12px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
		
		&.upload-card {
			border-left: 4px solid #667eea;
		}
		
		.card-header {
			display: flex;
			align-items: center;
			gap: 12px;
			margin-bottom: 8px;
			
			.card-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}
		}
		
		.card-desc {
			font-size: 14px;
			color: #666;
			line-height: 1.4;
		}
	}
}

.chat-section, .recent-section {
	padding: 0 20px 20px 20px;
	
	.section-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
		display: block;
	}
}

.quick-actions {
	display: flex;
	gap: 12px;
	margin-bottom: 20px;
	
	.action-btn {
		flex: 1;
		background: white;
		padding: 12px;
		border-radius: 8px;
		box-shadow: 0 1px 4px rgba(0,0,0,0.1);
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		
		.action-text {
			font-size: 14px;
			color: #333;
		}
	}
}

.suggestions {
	.suggestions-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 12px;
		display: block;
	}
	
	.question-list {
		.question-item {
			background: white;
			padding: 12px 15px;
			margin-bottom: 8px;
			border-radius: 8px;
			box-shadow: 0 1px 4px rgba(0,0,0,0.08);
			display: flex;
			align-items: center;
			gap: 10px;
			
			.question-text {
				font-size: 14px;
				color: #333;
				flex: 1;
			}
		}
	}
}

.results-list {
	.result-item {
		background: white;
		padding: 15px;
		margin-bottom: 10px;
		border-radius: 8px;
		box-shadow: 0 1px 4px rgba(0,0,0,0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		.result-info {
			flex: 1;
			
			.result-title {
				font-size: 16px;
				color: #333;
				display: block;
				margin-bottom: 4px;
			}
			
			.result-time {
				font-size: 12px;
				color: #999;
				display: block;
				margin-bottom: 6px;
			}
			
			.result-status {
				display: inline-block;
				
				.status-text {
					font-size: 12px;
					padding: 2px 8px;
					border-radius: 4px;
				}
				
				&.status-completed .status-text {
					background-color: #e8f5e8;
					color: #52c41a;
				}
				
				&.status-analyzing .status-text {
					background-color: #e6f7ff;
					color: #1890ff;
				}
				
				&.status-failed .status-text {
					background-color: #fff2f0;
					color: #ff4d4f;
				}
				
				&.status-pending .status-text {
					background-color: #f6f6f6;
					color: #999;
				}
			}
		}
	}
}

// 模态框样式
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.sport-type-modal {
	background: white;
	border-radius: 16px 16px 0 0;
	padding: 20px;
	width: 100%;
	animation: slideUp 0.3s ease-out;
	
	.modal-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		text-align: center;
		display: block;
		margin-bottom: 20px;
	}
	
	.sport-types {
		.sport-type-item {
			padding: 15px;
			border-bottom: 1px solid #f0f0f0;
			
			.sport-type-text {
				font-size: 16px;
				color: #333;
			}
			
			&:last-child {
				border-bottom: none;
			}
		}
	}
	
	.modal-actions {
		margin-top: 20px;
		
		.cancel-btn {
			width: 100%;
			background-color: #f5f5f5;
			color: #333;
			border: none;
			border-radius: 8px;
			padding: 12px;
			font-size: 16px;
		}
	}
}

.result-modal {
	background: white;
	border-radius: 16px 16px 0 0;
	padding: 20px;
	width: 100%;
	max-height: 70vh;
	animation: slideUp 0.3s ease-out;
	
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		
		.modal-title {
			font-size: 18px;
			font-weight: bold;
			color: #333;
		}
	}
	
	.result-content {
		.result-type {
			font-size: 20px;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 10px;
		}
		
		.result-summary {
			font-size: 15px;
			color: #666;
			line-height: 1.5;
			display: block;
			margin-bottom: 20px;
		}
		
		.result-actions {
			display: flex;
			gap: 10px;
			
			.action-btn {
				flex: 1;
				padding: 12px;
				border: none;
				border-radius: 8px;
				font-size: 16px;
				
				&.primary {
					background-color: #667eea;
					color: white;
				}
				
				&:not(.primary) {
					background-color: #f5f5f5;
					color: #333;
				}
			}
		}
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}
</style>
